<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\Text;
use plugin\admin\app\model\TextCategory;

class TextService
{
    public static function categories()
    {
        return TextCategory::all()->toArray();
    }

    public static function list($page = 1, $length = 10, $categoryId = 0)
    {
        $offset = ($page - 1) * $length;

        $query = Text::getQuery();

        if ($categoryId > 0) {
            $query->where('category_id', $categoryId);
        }

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->get()->toArray();


        foreach ($list as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $item['thumb'] = full_url($item['thumb']);
            $item['content'] = str_replace('src="/', 'src="' . getenv('APP_URL') . '/', $item['content']);
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function detail($id)
    {
        $detail = Text::where('id', $id)->first();
        $detail['thumb'] = full_url($detail['thumb']);
        $detail['content'] = str_replace('src="/', 'src="' . getenv('APP_URL') . '/', $detail['content']);

        return $detail;
    }

}